﻿//<input type="checkbox" name="parseurl" value="1" id="cb_parseurl" tabindex="1" checked="checked" />

chrome.extension.onRequest.addListener(function(request, sender, callback) {
	var selected = document.activeElement;
	var dialog = dom.createDialog('blog-insert', request.title);
	var list = dom.createList('post-list').disable();
	var blogUrl = request.url;
	var color = request.color;
	var insertButton = dom.createButton('insert-button', 'Insert', function(e) {
		var postUrl = list.selected().value;
		list.disable();
		insertButton.disable();
		dialog.showProgress();
		chrome.extension.sendRequest(
			{'action': 'getPost', 'id': postUrl },
			function(r) {
				var post = new postObject(r, blogUrl, postUrl, color);
				if (document.title && /Boise Riders/.test(document.title)) {
					selected.innerHTML = post.toBBCode();
				} else {
					selected.innerHTML = post.toBBHtml();
				}
				dom.get('cb_parseurl').checked = false;
				dialog.close();
			}
		);
	}).disable();
	
	dialog
		.append([list, insertButton])
		.positionBy(selected, 10)
		.showProgress();
	
	chrome.extension.sendRequest({'action': 'getBlog'},
		function(r) {
			list.enable();
			for (var i = 0; i < r.posts.length; i++) {
				list.append(r.posts[i].title, r.posts[i].url);
			}
			insertButton.enable();
			dialog.hideProgress();
		}
	);
});

// http://code.google.com/chrome/extensions/api_other.html
function postObject(html, blogUrl, postUrl, color) {
	var _postBeginsWith = '<div class=\'post-body';
	//var _postEndsWith = '<div class=\'post-footer';
	var _postEndsWith = '<fb:comments';
	var _mapDiv = '<div class="map">';
	var _blogUrl = blogUrl;
	var _postUrl = postUrl;
	var _textBox = null;
	var _text = parse(html);

	function parse(raw) {
		var text = raw.substring(raw.indexOf(_postBeginsWith), raw.indexOf(_postEndsWith));
		// find start
		var start = text.indexOf('<p>');
		var quoteStart = text.indexOf('<blockquote>');
		if (quoteStart >= 0 && quoteStart < start) { start = quoteStart; }
		// find end
		var p = '</p>';
		var bq = '</blockquote>';
		var end = text.lastIndexOf(p);
		var quoteEnd = text.lastIndexOf(bq);
		end = (quoteEnd >=0 && quoteEnd > end) ? quoteEnd + bq.length : end + p.length;
		// cut content
		return text.substr(start, end - start);
	}
	
	this.toBBHtml = function() {
		var endStyle = '">';
		var footerLinkStyle = 'style="color: #999;"';
		var text = replaceSpecialCharacters(_text);
		
		// block quote
		text = text.replace(/<blockquote>/gi, '<blockquote style="' +
			'background-image: url(http://www.trailimage.com/image/left-quote.png); ' +
			'background-repeat: no-repeat; ' +
			'background-position: left top; ' +
			'margin: 1em 7em; ' +
			'line-height: 1.2em; ' +
			'color: #aaa;' + endStyle);
			
		// image tag
		text = text.replace(/<div class=['"]photo['"]>\s*<div class=['"]frame['"]>\s*<img/gi,
			'<div class="photo"><div class="frame"><img style="' +
				'border: 1px solid #000; ' +
				'background-color: #fff; ' +
				'padding: 4px; ' +
				'margin: 0 0;"');
		
		// image caption
		text = text.replace(/(<div class=['"]photo['"]>\s*<div class=['"]frame['"]>\s*<img[^>]+>)\s*<p>/gi,
			'$1<p style="' +
				'display: block; ' +
				'font-family: Trebuchet MS, Arial, sans serif; ' +
				'font-size: 12pt; ' +
				'color: #999; ' +
				'text-align: center; ' +
				'padding-bottom: 2px; ' +
				'margin-bottom: 0.5em;' + endStyle);
		
		// image containers
		text = text.replace(/<div class=['"]photo['"]>\s*/gi, '<div style="' +
			'text-align: center; ' +
			'position: relative; ' +
			'margin: 0.5em 0; ' +
			'padding: 0;' + endStyle);
			
		text = text.replace(/<div class=['"]frame['"]>\s*/gi, '<div style="' +
			'text-align: center; ' +
			'position: relative; ' +
			'padding: 0;' + endStyle);
			
		// paragraphs
		text = text.replace(/<p>/gi, '<p style="' +
			'text-indent: 3em; ' +
			'margin: 0 6em 1em 5em; ' +
			'padding: 0;' + endStyle);
			
		// map
		text = text.replace(
			/(<div class=['"]map['"]>)\s*<iframe/gi,
			'$1<iframe style="border: 1px solid black;"');
		
		text = text.replace(/<div class=['"]map['"]>/gi, '<div style="' +
			'text-align: center; ' +
			'margin-bottom: 1em;' + endStyle);
			
		text = text.replace(/<small>\s*<a style=["'][^'"]+['"]/gi, '<small><a style="' +
			'text-align: center; ' +
			'font-size: 8pt; ' +
			'line-height: 1em; ' +
			'font-family: Verdana, sans-serif;"');
			
		// footer
		text += '<div style="' +
			'line-height: 1.1em; ' +
			'text-align: right; ' +
			'color: #888; ' +
			'font-size: 9pt; ' +
			'font-family: Tahoma, Arial;' + endStyle;
		text += 'these images are hosted at <a ' + footerLinkStyle +
			' href="http://flickr.com/photos/boise/">flickr</a> ■<br/>';
		text += 'this post was automatically generated from <a ' + footerLinkStyle +
			' href="' + _postUrl + '">my blog</a> ■<br/>';
		text += 'text and images are © Copyright ' + (new Date()).getFullYear() + ' Jason Abbott. All Rights Reserved. ■'
		text += '</div>';
			
		return '<div style="' +
			'font: normal normal 14pt Georgia, Times New Roman, Sans-Serif;' +
			'line-height: 1.2em; ' +
			'margin: 0;' +
			'">' + text + '</div>';
	}
	
	this.toBBCode = function() {
		var indentStart = '[indent][indent][indent][indent]';
		var indentEnd = '[/indent][/indent][/indent][/indent]';
		var text = convertHtmlToBBCode(_text);
		text = replaceSpecialCharacters(text);
		
		// link
		text = text.replace(/<a href="([^"]+)">([^<]+)<\/a>/gi, '[url=$1]$2[/url]');
		// image
		// <div class="photo"><img alt="blue5569477742" src="http://farm6.static.flickr.com/5026/5569477742_a98f2efbce_b.jpg" /></div>
		// <div class="photo"><img alt="5606501283" src="http://farm6.static.flickr.com/5183/5606501283_612a582da2_o.jpg" /><p>planned if not actual route</p></div>
		text = text.replace(
			/<div class=['"]photo['"]>\s*<div class=['"]frame['"]>\s*<img(\salt=['"][^"']+['"]\s)?src=["']([^"']+)["'](\salt=['"][^"']+['"])?\s*\/>\s*<\/div>\s*<\/div>/gi,
			indentEnd + '\r\n[center]\r\n[img]$2[/img][/center]' + indentStart);
		// image with caption
		text = text.replace(
			/<div class=['"]photo['"]>\s*<div class=['"]frame['"]>\s*<img(\salt=['"][^"']+['"]\s)?src=["']([^"']+)["'](\salt=['"][^"']+['"])?\s*\/>\s*<([^>]+)>([^<]+)<\/\4>\s*<\/div>\s*<\/div>/gi,
			indentEnd + '\r\n[center]\r\n[img]$2[/img]\r\n[color="Gray"]$5[/color][/center]' + indentStart);
		
		// paragraphs
		text = text.replace(/\s*<\/?p>\s*/gi, '\r\n');
		
		// map
		start = text.indexOf(_mapDiv);
		if (start > 0) {
			text = text.replace(_mapDiv, '[center]');
			end = text.indexOf('</div>', start);
			text = text.substring(0, end) + '[/center]' + text.substring(end + 6);
		}
		text = indentStart + text + indentEnd;
		
		// footer
		text += '[right][color=#999]';
		text += 'these images are hosted at [url=http://flickr.com/photos/boise/]flickr[/url] ■';
		text += '\r\nthis post was automatically generated from [url=' + _postUrl + ']my blog[/url] ■';
		text += '\r\ntext and images are © Copyright ' + (new Date()).getFullYear() + ' Jason Abbott. All Rights Reserved. ■'
		text += '[/color][/right]';
		
		return text;
	}
	
	function convertHtmlToBBCode(text) {
		var matrix = {
			'em': 'i',
			'strong': 'b',
			'blockquote': 'quote'
		};
		for (h in matrix) {
			text = text.replace(
				new RegExp('<(/?)' + h + '>', 'gi'),
				'[$1' + matrix[h] + ']'
			);
		}
		return text;
	}
	
	function replaceSpecialCharacters(text) {
		text = text.replace('&#8217;', '’');
		text = text.replace('&#8230;', '…');
		text = text.replace('&#8220;', '“');
		text = text.replace('&#8221;', '”');
		text = text.replace('&#8212;', '—');
		text = text.replace('&amp;', '&');
		text = text.replace('&#160;', ' ');
		return text;
	}
}